import {defineStore} from 'pinia'
import {createUser, deleteUser, fetchUserList, getUserDetail, updateUser} from '@/api/user.js'

export const useUserStore = defineStore('user', {
    state: () => ({
        userList: [],
        total: 0,
        searchParams: {},
        currentUser: null
    }),

    actions: {
        async fetchUser(params) {
            const response = await fetchUserList(params)
            this.userList = response.data.records
            this.total = response.data.total
            return response
        },

        async getUserDetail(id) {
            const response = await getUserDetail(id)
            return response
        },

        async createUser(data) {
            const response = await createUser(data)
            return response
        },

        async updateUser(id, data) {
            const response = await updateUser(data)
            return response
        },

        async deleteUser(id) {
            const response = await deleteUser(id)
            // 删除成功后从列表中移除
            this.userList = this.userList.filter(item => item.id !== id)
            this.total -= 1
            return response
        },

        setSearchParams(params) {
            this.searchParams = { ...params }
        },

        resetSearchParams() {
            this.searchParams = {}
        }
    }
})